package com.mobilecontrol;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.mobilecontrol.Entity.CtrlCmd;
import com.mobilecontrol.Events.ServerEvent;
import com.mobilecontrol.Listener.ControlListener;
import com.mobilecontrol.server.MobileServer;
import com.mobilecontrol.tool.CSJToast;
import com.mobilecontrol.tool.Contant;
import com.mobilecontrol.tool.SharedPreferencesUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, View.OnLongClickListener {
    public static final int TOP = 0;
    public static final int BOTTOM = 1;
    public static final int LEFT = 2;
    public static final int RIGHT = 3;
    private ControlListener mControlSendListener;
    private Button mSend, arrow_top, arrow_left, arrow_bottom,
            arrow_right, btn_smile, btn_cry, btn_wave_left, btn_wave_right;
    private EditText mEditText;
    private boolean isSend;
    private MainActivity mContext;
    private String[] contantItem = new String[]{Contant.BTN_1, Contant.BTN_2, Contant.BTN_3, Contant.BTN_4, Contant.BTN_5,
            Contant.BTN_6, Contant.BTN_7, Contant.BTN_8, Contant.BTN_9, Contant.BTN_10, Contant.BTN_11, Contant.BTN_12,
            Contant.BTN_13, Contant.BTN_14, Contant.BTN_15};
    private int[] buttonId = new int[]{com.mobilecontrol.R.id.btn_1, com.mobilecontrol.R.id.btn_2, com.mobilecontrol.R.id.btn_3, com.mobilecontrol.R.id.btn_4, com.mobilecontrol.R.id.btn_5, com.mobilecontrol.R.id.btn_6,
            com.mobilecontrol.R.id.btn_7, com.mobilecontrol.R.id.btn_8, com.mobilecontrol.R.id.btn_9, com.mobilecontrol.R.id.btn_10, com.mobilecontrol.R.id.btn_11, com.mobilecontrol.R.id.btn_12, com.mobilecontrol.R.id.btn_13,
            com.mobilecontrol.R.id.btn_14, com.mobilecontrol.R.id.btn_15};
    private List<Button> buttonList = new ArrayList<>();
    private TextView tv_state;
    private String mCmd;
    private boolean isStop;
    private boolean isLongClick;

    private MobileServer server;
    private EventBus eventBus;

    private Handler mMhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case TOP:
                    if (!isStop) {
                        arrow_top.performClick();
                    }
                    mMhandler.sendEmptyMessageDelayed(TOP, 700);
                    break;
                case BOTTOM:
                    if (!isStop) {
                        arrow_bottom.performClick();
                    }
                    mMhandler.sendEmptyMessageDelayed(BOTTOM, 700);
                    break;
                case LEFT:
                    if (!isStop) {
                        arrow_left.performClick();
                    }
                    mMhandler.sendEmptyMessageDelayed(LEFT, 700);
                    break;
                case RIGHT:
                    if (!isStop) {
                        arrow_right.performClick();
                    }
                    mMhandler.sendEmptyMessageDelayed(RIGHT, 700);
                    break;
            }

        }
    };

    @Override

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(com.mobilecontrol.R.layout.activity_main);
        mContext = this;
        initView();
        initButtonText();
        initLongPress();
        initLongClickListener();
        server = MobileServer.getInstance();
        if (eventBus == null) {
            eventBus = EventBus.getDefault();
        }
        eventBus.register(this);
    }

    @Override
    protected void onDestroy() {
        if (eventBus != null) {
            eventBus.unregister(this);
        }
        super.onDestroy();
    }

    private void initButtonText() {

        for (int i = 0; i < contantItem.length; i++) {
            String cmd = (String) SharedPreferencesUtils.getParam(mContext, contantItem[i], "");
            if (!TextUtils.isEmpty(cmd)) {
                buttonList.get(i).setText(cmd);
            }
        }
    }

    private void initLongClickListener() {
        for (Button button : buttonList) {
            button.setOnLongClickListener(this);
        }

    }

    private void initLongPress() {
        // TODO: 2017-09-21 上连击
        arrow_top.setOnTouchListener(new View.OnTouchListener() {
            private long mDown_time;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDown_time = System.currentTimeMillis();
                        isLongClick = false;
                        isStop = false;
                        mMhandler.sendEmptyMessageDelayed(TOP, 700);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - mDown_time > 300) {
                            isLongClick = true;
                        }
                        isStop = true;
                        mMhandler.removeMessages(TOP);
                        break;
                }
                return false;
            }
        });
        // TODO: 2017-09-21 左连击
        arrow_left.setOnTouchListener(new View.OnTouchListener() {
            private long mDown_time;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDown_time = System.currentTimeMillis();
                        isLongClick = false;
                        isStop = false;
                        mMhandler.sendEmptyMessageDelayed(LEFT, 700);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - mDown_time > 300) {
                            isLongClick = true;
                        }
                        isStop = true;
                        mMhandler.removeMessages(LEFT);
                        break;
                }
                return false;
            }
        });
        // TODO: 2017-09-21 下连击
        arrow_bottom.setOnTouchListener(new View.OnTouchListener() {
            private long mDown_time;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDown_time = System.currentTimeMillis();
                        isLongClick = false;
                        isStop = false;
                        mMhandler.sendEmptyMessageDelayed(BOTTOM, 700);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - mDown_time > 300) {
                            isLongClick = true;
                        }
                        isStop = true;
                        mMhandler.removeMessages(BOTTOM);
                        break;
                }
                return false;
            }
        });
        // TODO: 2017-09-21 右连击
        arrow_right.setOnTouchListener(new View.OnTouchListener() {
            private long mDown_time;

            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                switch (motionEvent.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        mDown_time = System.currentTimeMillis();
                        isLongClick = false;
                        isStop = false;
                        mMhandler.sendEmptyMessageDelayed(RIGHT, 700);
                        break;
                    case MotionEvent.ACTION_UP:
                        if (System.currentTimeMillis() - mDown_time > 300) {
                            isLongClick = true;
                        }
                        isStop = true;
                        mMhandler.removeMessages(RIGHT);
                        break;
                }
                return false;
            }
        });

    }

    private void initView() {
        mEditText = (EditText) findViewById(com.mobilecontrol.R.id.et_con);
        mSend = (Button) findViewById(com.mobilecontrol.R.id.btn_send);
        for (int id : buttonId) {
            buttonList.add((Button) findViewById(id));
        }
        arrow_top = (Button) findViewById(com.mobilecontrol.R.id.arrow_top);
        arrow_left = (Button) findViewById(com.mobilecontrol.R.id.arrow_left);
        arrow_bottom = (Button) findViewById(com.mobilecontrol.R.id.arrow_bottom);
        arrow_right = (Button) findViewById(com.mobilecontrol.R.id.arrow_right);
        btn_smile = (Button) findViewById(com.mobilecontrol.R.id.btn_smile);
        btn_cry = (Button) findViewById(com.mobilecontrol.R.id.btn_cry);
        btn_wave_left = (Button) findViewById(com.mobilecontrol.R.id.btn_wave_left);
        btn_wave_right = (Button) findViewById(com.mobilecontrol.R.id.btn_wave_right);
        mSend.setOnClickListener(this);

        tv_state = (TextView) findViewById(com.mobilecontrol.R.id.tv_state);

        for (Button button : buttonList) {
            button.setOnClickListener(this);
        }

        arrow_top.setOnClickListener(this);
        arrow_left.setOnClickListener(this);
        arrow_bottom.setOnClickListener(this);
        arrow_right.setOnClickListener(this);
        btn_smile.setOnClickListener(this);
        btn_cry.setOnClickListener(this);
        btn_wave_left.setOnClickListener(this);
        btn_wave_right.setOnClickListener(this);

    }


    private void sendMessage(CtrlCmd cmd) {
        String jsonString = JSON.toJSONString(cmd);
        server.sendMsg(jsonString);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case com.mobilecontrol.R.id.btn_send:
                isSend = true;
                String control = mEditText.getText().toString().trim();
                if (TextUtils.isEmpty(control)) {
                    CSJToast.showToast(mContext, "命令不能为空，请重新输入");
                    break;
                }
                CSJToast.showToast(mContext, "命令已发送");
//                mEditText.setText("");
                // TODO: 2017-09-21  处理逻辑
                if (mControlSendListener != null) {
                    mControlSendListener.sendCmd(control);
                }

                CtrlCmd cmd = new CtrlCmd(0, control);
                sendMessage(cmd);
                break;
            case com.mobilecontrol.R.id.btn_1:
                mCmd = buttonList.get(0).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_2:
                mCmd = buttonList.get(1).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_3:
                mCmd = buttonList.get(2).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_4:
                mCmd = buttonList.get(3).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_5:
                mCmd = buttonList.get(4).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_6:
                mCmd = buttonList.get(5).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_7:
                mCmd = buttonList.get(6).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_8:
                mCmd = buttonList.get(7).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_9:
                mCmd = buttonList.get(8).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_10:
                mCmd = buttonList.get(9).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_11:
                mCmd = buttonList.get(10).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_12:
                mCmd = buttonList.get(11).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_13:
                mCmd = buttonList.get(12).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_14:
                mCmd = buttonList.get(13).getText().toString().trim();

                break;
            case com.mobilecontrol.R.id.btn_15:
                mCmd = buttonList.get(14).getText().toString().trim();
                break;
            // TODO: 2017-09-21 上下左右
            case com.mobilecontrol.R.id.arrow_top:
                if (!isLongClick) {
                    if (mControlSendListener != null) {
                        mControlSendListener.front();
                    }
                }
                break;
            case com.mobilecontrol.R.id.arrow_left:
                if (!isLongClick) {
                    if (mControlSendListener != null) {
                        mControlSendListener.turnLeft();
                    }
                }
                break;
            case com.mobilecontrol.R.id.arrow_bottom:
                if (!isLongClick) {
                    if (mControlSendListener != null) {
                        mControlSendListener.back();
                    }
                }
                break;
            case com.mobilecontrol.R.id.arrow_right:
                if (!isLongClick) {
                    if (mControlSendListener != null) {
                        mControlSendListener.turnRight();
                    }
                }
                break;
            // TODO: 2017-09-21 哭笑挥左挥右
            case com.mobilecontrol.R.id.btn_smile:
                if (mControlSendListener != null) {
                    mControlSendListener.smile();
                }
                break;
            case com.mobilecontrol.R.id.btn_cry:
                if (mControlSendListener != null) {
                    mControlSendListener.cry();
                }
                break;
            case com.mobilecontrol.R.id.btn_wave_left:
                if (mControlSendListener != null) {
                    mControlSendListener.waveLeft();
                }
                break;
            case com.mobilecontrol.R.id.btn_wave_right:
                if (mControlSendListener != null) {
                    mControlSendListener.waveRight();
                }
                break;
            default:
                break;
        }
        if (!TextUtils.isEmpty(mCmd) && !isSend) {
            mEditText.setText(mCmd);
            mEditText.setSelection(mCmd.length());
        }
        isSend = false;
    }

    @Override
    public boolean onLongClick(View view) {
        Editable control = mEditText.getText();
        String cmd = String.valueOf(control);
        if (TextUtils.isEmpty(cmd)) {
            CSJToast.showToast(MainActivity.this, "命令不能为空，请重新输入");
            return true;
        }
        switch (view.getId()) {
            case com.mobilecontrol.R.id.btn_1:
                SharedPreferencesUtils.setParam(mContext, contantItem[0], cmd);
                buttonList.get(0).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_2:
                SharedPreferencesUtils.setParam(mContext, contantItem[1], cmd);
                buttonList.get(1).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_3:
                SharedPreferencesUtils.setParam(mContext, contantItem[2], cmd);
                buttonList.get(2).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_4:
                SharedPreferencesUtils.setParam(mContext, contantItem[3], cmd);
                buttonList.get(3).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_5:
                SharedPreferencesUtils.setParam(mContext, contantItem[4], cmd);
                buttonList.get(4).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_6:
                SharedPreferencesUtils.setParam(mContext, contantItem[5], cmd);
                buttonList.get(5).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_7:
                SharedPreferencesUtils.setParam(mContext, contantItem[6], cmd);
                buttonList.get(6).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_8:
                SharedPreferencesUtils.setParam(mContext, contantItem[7], cmd);
                buttonList.get(7).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_9:
                SharedPreferencesUtils.setParam(mContext, contantItem[8], cmd);
                buttonList.get(8).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_10:
                SharedPreferencesUtils.setParam(mContext, contantItem[9], cmd);
                buttonList.get(9).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_11:
                SharedPreferencesUtils.setParam(mContext, contantItem[10], cmd);
                buttonList.get(10).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_12:
                SharedPreferencesUtils.setParam(mContext, contantItem[11], cmd);
                buttonList.get(11).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_13:
                SharedPreferencesUtils.setParam(mContext, contantItem[12], cmd);
                buttonList.get(12).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_14:
                SharedPreferencesUtils.setParam(mContext, contantItem[13], cmd);
                buttonList.get(13).setText(cmd);
                break;
            case com.mobilecontrol.R.id.btn_15:
                SharedPreferencesUtils.setParam(mContext, contantItem[14], cmd);
                buttonList.get(14).setText(cmd);
                break;
        }
        CSJToast.showToast(MainActivity.this, "已保存命令");
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void serverStateChanged(ServerEvent event) {
        if (event.getTag() == ServerEvent.CLIENT_CONNECTED) {
            tv_state.setText("客户端已经连接 " + event.getMegString());
        }
        if (event.getTag() == ServerEvent.CLIENT_DISCONNECTED) {
            tv_state.setText("等待连接");
        }
    }

}
